package com.seeyon.ctp.rest.resources;

import com.alibaba.fastjson.JSON;
import com.seeyon.apps.zjzd.Kit.FileUtilKit;
import com.seeyon.apps.zjzd.Kit.HttpKit;
import com.seeyon.apps.zjzd.Kit.StrKit;
import com.seeyon.cap4.form.bean.*;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.formula.FormulaUtil;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.UUIDLong;
import org.apache.commons.logging.Log;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Path("jssdk")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON})
public class BatchDownloadResources extends BaseResource {

    private static final Log log = CtpLogFactory.getLog(BatchDownloadResources.class);

    private OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
    private FileManager fileManager = (FileManager) AppContext.getBean("fileManager");
    private AttachmentDAO attachmentDAO = (AttachmentDAO) AppContext.getBean("attachmentDAO");
    private AttachmentManager attachmentManager = (AttachmentManager) AppContext.getBean("attachmentManager");
    private CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");


    /**
     * 批量下载附件接口
     *
     * 该方法接收一个包含数据ID集合的参数，根据这些ID获取相关的附件信息，
     * 并将这些附件打包成一个ZIP文件，最后返回ZIP文件的下载URL
     *
     * @param param 包含需要下载的附件数据ID集合的映射对象
     * @return 返回一个包含下载结果和URL的响应对象
     * @throws BusinessException 当业务处理过程中遇到异常时抛出
     */
    @POST
    @Path("batch/download/attachments")
    public Response addDataIds(Map<String, Object> param) throws BusinessException {
        // 记录需要下载附件的数据ID集合
        log.info("需要下载附件数据ID集合：" + JSON.toJSONString(param));
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            // 根据表单代码获取表单对象
            FormBean formBean = cap4FormManager.getFormByFormCode("QZXXB_001");
            // 获取并处理数据ID集合字符串
            String dataIds = StrKit.str(param.get("ids"));
            dataIds = dataIds.replaceAll("\\[", "").replaceAll("\\]", "");
            String[] dataIdArr = dataIds.split(",");
            String memberCode = "";
            String loginName = "";
            // 遍历数据ID数组，获取每个数据项的附件信息
            for (String dataId : dataIdArr) {
                FormDataMasterBean formDataMasterBean = cap4FormManager.getDataMasterBeanById(Long.parseLong(dataId.trim()), formBean, null);
                // 获取员工号、登录名和各种附件ID
                memberCode = StrKit.str(formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("员工号").getName()));
                loginName = orgManager.getMemberById(formDataMasterBean.getStartMemberId()).getLoginName();
                // 下载签证附件
                String visaId = StrKit.str(formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("签证").getName()));
                if (!"".equals(visaId)) {
                    attachmentDownload(visaId, loginName, memberCode);
                }
                // 下载身份证附件
                String idcarId = StrKit.str(formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("ID卡").getName()));
                if (!"".equals(idcarId)) {
                    attachmentDownload(idcarId, loginName, memberCode);
                }
                // 下载护照附件
                String passportId = StrKit.str(formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("护照").getName()));
                if (!"".equals(passportId)) {
                    attachmentDownload(passportId, loginName, memberCode);
                }
                // 下载照片附件
                String pictureId = StrKit.str(formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("照片").getName()));
                if (!"".equals(pictureId)) {
                    attachmentDownload(pictureId, loginName, memberCode);
                }
            }
            // 构建系统文件路径和ZIP文件路径
            String systemUrl = SystemEnvironment.getBaseFolder().replaceAll("\\\\", "/");
            String pathUrl = systemUrl + "/upload/customFile/download/";
            String zipUrl = systemUrl + "/upload/customFile/zip/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
            File file = new File(zipUrl);
            file.getParentFile().mkdirs();
            // 将附件打包成ZIP文件，并删除原文件
            FileUtilKit.toZip(pathUrl, zipUrl, true);
            FileUtilKit.deleteFiles(new File(pathUrl));
            // 生成附件下载的URL
            long refId = UUIDLong.longUUID();
            V3XFile v3XFile = fileUpload(loginName, file, refId);
            String attUrl = "/seeyon/rest/attachment/file/" + v3XFile.getId() + "?fileName=" + v3XFile.getFilename();
            // 构建返回结果
            resultMap.put("code", 200);
            resultMap.put("msg", "附件下载成功!");
            resultMap.put("url", attUrl);
            // 记录接口返回结果
            log.info("附件下载接口返回结果:" + JSON.toJSONString(resultMap));
        } catch (Exception e) {
            // 记录异常信息
            log.error("附件批量下载接口异常信息:", e);
            resultMap.put("code", 500);
            resultMap.put("msg", e.getMessage());
            resultMap.put("url", "");
        }
        return ok(resultMap);
    }

    /**
     * 根据附件ID下载附件
     *
     * @param subReference 附件ID，用于获取附件列表
     * @param loginName 登录名，用于获取Token
     * @param memberCode 会员代码，用于下载附件时标识会员
     * @throws BusinessException 当附件下载过程中发生业务异常时抛出
     */
    private void attachmentDownload(String subReference, String loginName, String memberCode) throws BusinessException {
        try {
            // 根据子引用（身份证ID）获取附件ID列表
            List<Long> fileIdList = attachmentManager.getBySubReference(Long.parseLong(subReference));
            // 获取基础URL
            String url = StrKit.str(FormulaUtil.getVar("url"));
            // 拼接Token获取URL
            String tokenUrl = url + "/seeyon/rest/token";
            // 获取Token ID
            String tokenId = HttpKit.getToken(loginName, tokenUrl);
            // 如果附件ID列表不为空，则遍历下载每个附件
            if (!fileIdList.isEmpty()) {
                for (Long fileId : fileIdList) {
                    // 根据文件ID获取文件信息
                    V3XFile v3XFile = fileManager.getV3XFile(fileId);
                    // 拼接附件下载URL
                    String attUrl = url + "/seeyon/rest/attachment/file/" + v3XFile.getId() + "?fileName=" + URLEncoder.encode(v3XFile.getFilename(), "UTF-8") + "&token=" + tokenId + "";
                    // 下载附件
                    File file = HttpKit.downloadFile(attUrl, new HashMap<String, Object>(), memberCode, v3XFile.getFilename());
                }
            }
        } catch (Exception e) {
            // 记录附件下载失败的日志
            log.error("附件下载失败:", e);
        }
    }

    /**
     * 文件上传方法
     *
     * @param loginName 用户登录名，用于获取上传token
     * @param file 要上传的文件
     * @param refId 文件的引用ID，用于关联业务数据
     * @return 返回上传成功的V3XFile对象
     * @throws BusinessException 当文件上传过程中发生业务异常时抛出
     */
    private V3XFile fileUpload(String loginName, File file, Long refId) throws BusinessException {
        V3XFile v3xFile = null;
        try {
            // 获取上传服务的URL和Token
            String url = StrKit.str(FormulaUtil.getVar("url"));
            String tokenUrl = url + "/seeyon/rest/token";
            String tokenId = HttpKit.getToken(loginName, tokenUrl);

            // 构造文件上传的完整URL
            String fileUrl = url + "/seeyon/rest/attachment?token=" + tokenId;

            // 执行文件上传并获取上传结果
            String fileResult = HttpKit.uploadFile(fileUrl, file);
            log.info("附件上传成功返回信息:" + fileResult);

            // 删除已上传的本地文件
            file.delete();

            // 解析上传结果中的文件URL并获取V3XFile对象
            String fileUrl_oa = StrKit.getFileUrl(fileResult);
            v3xFile = fileManager.getV3XFile(Long.parseLong(fileUrl_oa));

            // 创建并初始化Attachment对象，用于保存文件上传的元数据
            Attachment attachment = new Attachment();
            attachment.setIdIfNew();
            attachment.setCategory(66);
            attachment.setCreatedate(v3xFile.getCreateDate());
            attachment.setDescription(v3xFile.getDescription());
            attachment.setFilename(v3xFile.getFilename());
            attachment.setFileUrl(v3xFile.getId());
            attachment.setReference(refId);
            Long sub_reference = UUIDLong.longUUID();
            attachment.setSubReference(sub_reference);
            attachment.setSort(1);
            attachment.setType(v3xFile.getType());
            attachment.setMimeType(v3xFile.getMimeType());
            attachment.setSize(v3xFile.getSize());

            // 保存文件上传的元数据到数据库
            attachmentDAO.save(attachment);
        } catch (Exception e) {
            log.error("附件上传失败:", e);
        }
        return v3xFile;
    }

}
